/*
	Copyright 2008 Marco Mustapic
	
    This file is part of Agilar GWT Widgets.

    Agilar GWT Widgets is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Agilar GWT Widgets is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Agilar GWT Widgets.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.agilar.gwt.sortabletable;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.Widget;

public class SortableTable extends FlexTable implements TableListener
{
	private TableModel model;
	private boolean ascending = false;
	private int sortColumn = -1;
	
	private int rows = 0;
	private int columns = 0;
	
	public SortableTable()
	{
		super();
		addTableListener(this);
	}
	
	public TableModel getModel()
	{
		return model;
	}

	public void setModel(TableModel model)
	{
		this.model = model;
		
		int newRows = model.getRowCount();
		int newColumns = model.getColumnCount();
		
		// rebuild UI
		buildTable();
		
		for (int row=newRows; row<this.rows; row++)
		{
			removeRow(row+1);
		}

		for (int col=newColumns; col<this.columns; col++)
		{
			for (int row=0; row<newRows+1; row++)
			{
				removeCell(row, col);
			}
		}

		this.rows = newRows;
		this.columns = newColumns;
	}

	private void buildTable()
	{
		for (int col=0; col<model.getColumnCount(); col++)
		{
			Label label = new Label(model.getColumnName(col));
			setWidget(0, col, label);
		}
		
		buildCells();
	}

	private void buildCells()
	{
		for (int row=0; row<model.getRowCount(); row++)
		{
			for (int col=0; col<model.getColumnCount(); col++)
			{
				setWidget(row+1, col, (Widget)model.get(row, col));
			}			
		}
	}

	public void onCellClicked(SourcesTableEvents source, int row, int column)
	{
		if (row == 0)
		{
			if (sortColumn != column)
			{
				ascending = true;
			}
			else
			{
				ascending = !ascending;
			}
			
			sort(column, ascending);
		}
	}
	
	public void sort(int column, boolean ascending)
	{
		this.sortColumn = column;
		this.ascending = ascending;
		model.sort(column, ascending);
		buildCells();
	}
}
